package com.tanglongan.concurrent.thread;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class YieldDemo {


    public static final int MAX_TURN = 100;                             //执行次数
    public static AtomicInteger index = new AtomicInteger(0);           //执行编号
    private static final Map<String, AtomicInteger> metric = new HashMap<>(); //记录线程的执行次数

    private static void printMetric() {
        System.out.println("metric = " + metric);
    }

    static class YieldThread extends Thread {
        static int threadSeqNumber = 1;

        public YieldThread() {
            super("YieldThread-" + threadSeqNumber);
            threadSeqNumber++;
            metric.put(this.getName(), new AtomicInteger(0));
        }

        @Override
        public void run() {
            for (int i = 1; i < MAX_TURN && index.get() < MAX_TURN; i++) {
                System.out.println("线程优先级:" + getPriority());
                index.incrementAndGet();
                metric.get(this.getName()).incrementAndGet();
                if (i % 2 == 0) {
                    Thread.yield();//当前线程让出执行机会
                }
            }
            System.out.println(getName() + " 运行结束.");
        }
    }

    private static void sleepSeconds(int l) {
        LockSupport.parkNanos(l * 1000L * 1000L * 1000L);
    }

    public static void main(String[] args) {
        Thread thread1 = new YieldThread();
        thread1.setPriority(Thread.MAX_PRIORITY);

        Thread thread2 = new YieldThread();
        thread2.setPriority(Thread.MIN_PRIORITY);

        System.out.println("启动线程");
        thread1.start();
        thread2.start();

        sleepSeconds(10);
        System.out.println("Metric:" + JSON.toJSONString(metric));
    }

}
